package com.zcsy.commons.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.PropertiesUtil;

/**
 * @Title: AliyunOssUtil.java
 * @Package： com.zcsy.commons.upload 
 * @Description: 阿里云文件上传工具类接口实现
 *
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年5月4日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
public class AliyunOssUtil {

    private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");
    
    private static String endpoint = propertiesUtil.getProperty("OSS_ENDPOINT");
    private static String accessId= propertiesUtil.getProperty("ACCESS_ID");
    private static String accessKey= propertiesUtil.getProperty("ACCESS_KEY");
    private static String bucketName= propertiesUtil.getProperty("bucketName");
	static Log log = LogFactory.getLog(AliyunOssUtil.class);  
	
	public static void save(String key,String filePath){   
		try{    
			// 使用默认的OSS服务器地址创建OSSClient对象        
			System.out.println(endpoint);
			OSSClient client = new  OSSClient(endpoint,accessId,accessKey); 
			ensureBucket(client, bucketName);         
			setBucketPublicReadable(client,bucketName);          
			System.out.println("正在上传...");        
			//fileName = System.currentTimeMillis() + "." +getExtensionName(fileName);         
			//uploadFile(client,bucketName, key, filePath);    
			}catch(Exception e){     
				log.error("上传失败");   
				}  
		} 
	
	 // 如果Bucket不存在，则创建它。     
	public static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException{           
		if (client.isBucketExist(bucketName)){        
			log.error("isBucketExist true");             
			return;         
			}          
		//创建bucket          
		client.createBucket(bucketName);    
		} 
	
	 // 删除一个Bucket和其中的Objects       
	public static void deleteBucket(OSSClient client, String bucketName)throws OSSException, ClientException {  
	        ObjectListing ObjectListing = client.listObjects(bucketName);         
	        List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();          
	        for (int i = 0; i < listDeletes.size(); i++) {              
	        	String objectName = listDeletes.get(i).getKey();            
	        	// 如果不为空，先删除bucket下的文件             
	        	client.deleteObject(bucketName, objectName);         
	        	}          
	        client.deleteBucket(bucketName);     
	   }
	
	 // 把Bucket设置为所有人可读     
	public static void setBucketPublicReadable(OSSClient client, String bucketName)throws OSSException, ClientException {         
		//创建bucket          
		client.createBucket(bucketName);           
		//设置bucket的访问权限，public-read-write权限        
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);     
		} 
	
	// 上传文件      
	public static Map<String, Object>  uploadFile(OSSClient client, String bucketName, String Objectkey, File file)throws OSSException, ClientException, FileNotFoundException {      
		ObjectMetadata objectMeta = new ObjectMetadata();         
			objectMeta.setContentLength(file.length());
		// 可以在metadata中标记文件类型       
		if (Objectkey.endsWith("xml")) {           
			objectMeta.setContentType("text/xml");          
		}else if (Objectkey.endsWith("jpg")) {           
			objectMeta.setContentType("image/jpeg");          
		}else if (Objectkey.endsWith("png")) {          
			objectMeta.setContentType("image/png");          
		}  
		InputStream input = null;
		try {
			input = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		//给文件重命名，格式为yyyymmddhhmmss.文件后缀
		Objectkey = DateUtils.getConfirmCurrentDate() + '.'+ Objectkey.substring(Objectkey.lastIndexOf(".")+1);
		String fileUrl = DateUtils.getCurrentDate()+'/'+Objectkey;
		client.putObject(bucketName, fileUrl, input,
				objectMeta);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("success", true);
		map.put("objectkey", fileUrl);
		return map;
	}
	
	private static long Long(int available) {
		// TODO Auto-generated method stub
		return 0;
	}

	public static void main(String args[]){      
		String key= "16.jpg";       
		String filePath="E:\\16.jpg";      
		save(key,filePath);   
		System.out.println(key);
	} 
}
